<?php


namespace App\Http\Middleware;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class TerminateTask {
    private static $_taskFnList = [];
    
    public static function addTaskFnList(callable $taskFn) {
        array_push(self::$_taskFnList, $taskFn);
    }
    
    public function handle(Request $request, \Closure $next) {
        return $next($request);
    }
    
    public function terminate($request, $response) {
    
        self::isDev() && Log::info('TerminateTask -任务执行中间件执行。');
    
        $taskFnCount = 0;
        while ($taskFn = array_shift(self::$_taskFnList)) {
            self::isDev() && Log::info('TerminateTask 执行计数：' . (++$taskFnCount));
    
            try {
                call_user_func_array($taskFn, []);
            } catch (\Exception $e) {
                Log::error('TerminateTask fail:' . $e->getMessage());
                Log::error($e->getTraceAsString());
            }
        }
    }
    
    /**
     * @return bool
     */
    protected static function isDev() {
        return env('APP_ENV') != 'production';
    }
}